/**
 * @file ESP32-SSD1306-MQTT.ino
 * @brief ESP32温湿度监测设备主程序
 * 
 * 功能概述：
 * - WiFi连接管理和自动重连
 * - MQTT通信和命令处理
 * - AHT10温湿度传感器数据采集
 * - OLED显示屏状态显示
 * - Web配置界面
 * - 按钮控制（单击切换显示，长按进入配网模式）
 * 
 * 硬件要求：
 * - ESP32开发板
 * - SSD1306 OLED显示屏 (128x64)
 * - AHT10温湿度传感器
 * - BOOT按钮 (GPIO0)
 * 
 * 作者: [您的名字]
 * 版本: 1.1.0
 * 日期: [当前日期]
 * 
 * 修复内容:
 * - 修复配网失败后无法重新开启AP模式的问题
 * - 优化配网流程和状态管理
 */

#include <WiFi.h>
#include <AsyncMqttClient.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_AHTX0.h>
#include <EEPROM.h>
#include <WebServer.h>
#include <ArduinoJson.h>

// 包含自定义头文件
#include "WiFiManager.h"
#include "MQTTManager.h"
#include "DisplayManager.h"
#include "AHT10Sensor.h"
#include "MQTTTopicManager.h"

// 全局管理器对象
WiFiManager wifiManager;
MQTTManager mqttManager;
DisplayManager displayManager;
AHT10Sensor aht10Sensor;

// ============================ 定时器配置 ============================
unsigned long lastSensorRead = 0;              ///< 上次传感器读取时间
unsigned long sensorReadInterval = 500;       ///< 传感器读取间隔(ms)

unsigned long lastWifiCheck = 0;               ///< 上次WiFi检查时间
const unsigned long WIFI_CHECK_INTERVAL = 5000; ///< WiFi检查间隔(ms)

unsigned long lastDisplayUpdate = 0;           ///< 上次显示更新时间
unsigned long displayUpdateInterval = 1000;    ///< 显示更新间隔(ms) - 改为变量

unsigned long lastPublishTime = 0;             ///< 上次数据发布时间
unsigned long publishInterval = 1000;          ///< 数据发布间隔(ms)

// ============================ 按钮配置 ============================
const int BOOT_BUTTON_PIN = 0;                 ///< BOOT按钮引脚(GPIO0)

// 长按检测变量
unsigned long buttonPressStartTime = 0;        ///< 按钮按下开始时间
bool buttonPressed = false;                    ///< 按钮按下状态
bool longPressDetected = false;                ///< 长按检测标志
const unsigned long LONG_PRESS_TIME = 3000;    ///< 长按时间阈值(ms)

// 单击检测变量
unsigned long lastButtonPressTime = 0;         ///< 上次按钮按下时间
bool lastButtonState = HIGH;                   ///< 上次按钮状态
const unsigned long DEBOUNCE_DELAY = 50;       ///< 防抖延时(ms)
const unsigned long CLICK_TIME = 500;          ///< 单击最大时间(ms)

// ============================ 系统状态 ============================
bool systemReady = false;                      ///< 系统就绪状态
bool mqttInitialized = false;                  ///< MQTT初始化状态

// ============================ MQTT重连配置 ============================
unsigned long lastMQTTReconnectAttempt = 0;    ///< 上次MQTT重连尝试时间
const unsigned long MQTT_RECONNECT_INTERVAL = 10000; ///< MQTT重连间隔(ms)
bool mqttReconnectInProgress = false;          ///< MQTT重连进行中标志
unsigned long mqttConnectStartTime = 0;        ///< MQTT连接开始时间
const unsigned long MQTT_CONNECT_TIMEOUT = 10000; ///< MQTT连接超时时间(ms)

// ============================ 状态检查配置 ============================
unsigned long lastStatusCheck = 0;             ///< 上次状态检查时间
const unsigned long STATUS_CHECK_INTERVAL = 1000; ///< 状态检查间隔(ms)

// ============================ 网络诊断 ============================
bool ipv6Available = false;                    ///< IPv6可用性标志

// ============================ 配网状态管理 ============================
bool configModeRequested = false;              ///< 配置模式请求标志
unsigned long configModeRequestTime = 0;       ///< 配置模式请求时间
const unsigned long CONFIG_MODE_RETRY_DELAY = 2000; ///< 配置模式重试延迟(ms)

// ============================ 函数声明 ============================
void initGPIO();
void checkButton();
void diagnoseNetwork();
void testDNSResolution();
void enterConfigMode();
bool initializeMQTT();
void handleMQTTReconnect();
void clearCorruptedEEPROM();
void handleConfigModeRetry();

/**
 * @brief 初始化GPIO引脚
 */
void initGPIO() {
  pinMode(BOOT_BUTTON_PIN, INPUT_PULLUP);  // BOOT按钮内部上拉
  Serial.println("GPIO initialization completed - BOOT button: GPIO0");
}

/**
 * @brief 检查按钮状态并处理单击和长按事件
 */
void checkButton() {
  int currentButtonState = digitalRead(BOOT_BUTTON_PIN);
  unsigned long currentTime = millis();

  // 检测按钮状态变化（下降沿：按下）
  if (currentButtonState == LOW && lastButtonState == HIGH) {
    lastButtonState = LOW;
    buttonPressStartTime = currentTime;
    buttonPressed = true;
    longPressDetected = false;
    Serial.println("BOOT button pressed, detecting long press and click...");
  }

  // 检测按钮状态变化（上升沿：释放）
  if (currentButtonState == HIGH && lastButtonState == LOW) {
    lastButtonState = HIGH;
    buttonPressed = false;

    unsigned long pressDuration = currentTime - buttonPressStartTime;

    // 单击检测：按压时间在50ms到500ms之间
    if (pressDuration >= DEBOUNCE_DELAY && pressDuration < CLICK_TIME && !longPressDetected) {
      Serial.println("BOOT button clicked - toggling display");
      displayManager.toggle();  // 切换屏幕亮灭状态
    }

    // 长按检测
    if (pressDuration >= LONG_PRESS_TIME) {
      longPressDetected = true;
      Serial.println("BOOT button long press detected - entering config mode");
      enterConfigMode();
    }
  }

  // 检测长按（在按钮持续按下时）
  if (buttonPressed && !longPressDetected) {
    if (currentTime - buttonPressStartTime >= LONG_PRESS_TIME) {
      longPressDetected = true;
      Serial.println("BOOT button long press detected - entering config mode");
      enterConfigMode();
    }
  }
}

/**
 * @brief 网络诊断函数
 */
void diagnoseNetwork() {
  Serial.println("=== Network Diagnostic Information ===");

  // WiFi状态
  Serial.print("WiFi status: ");
  switch (WiFi.status()) {
    case WL_CONNECTED: Serial.println("Connected"); break;
    case WL_NO_SHIELD: Serial.println("No WiFi module"); break;
    case WL_IDLE_STATUS: Serial.println("Idle status"); break;
    case WL_NO_SSID_AVAIL: Serial.println("SSID unavailable"); break;
    case WL_SCAN_COMPLETED: Serial.println("Scan completed"); break;
    case WL_CONNECT_FAILED: Serial.println("Connection failed"); break;
    case WL_CONNECTION_LOST: Serial.println("Connection lost"); break;
    case WL_DISCONNECTED: Serial.println("Disconnected"); break;
  }

  if (WiFi.status() == WL_CONNECTED) {
    // IPv4信息
    Serial.print("IPv4 address: ");
    Serial.println(WiFi.localIP());

    // IPv6信息
#ifdef CONFIG_LWIP_IPV6
    Serial.print("IPv6 link-local address: ");
    Serial.println(WiFi.linkLocalIPv6());

    Serial.print("IPv6 global address: ");
    Serial.println(WiFi.globalIPv6());
#else
    Serial.println("IPv6: Not enabled");
#endif

    // DNS信息
    Serial.print("DNS server: ");
    Serial.println(WiFi.dnsIP());

    // 网关
    Serial.print("Gateway: ");
    Serial.println(WiFi.gatewayIP());

    // 信号强度
    Serial.print("Signal strength: ");
    Serial.print(WiFi.RSSI());
    Serial.println(" dBm");
  }

  Serial.println("===================");
}

/**
 * @brief 测试DNS解析功能
 */
void testDNSResolution() {
  Serial.println("=== DNS Resolution Test ===");

  IPAddress ip;
  if (WiFi.hostByName("mosquitto.leeleo.cc", ip)) {
    Serial.print("mosquitto.leeleo.cc resolved to: ");
    Serial.println(ip);

    // 检查IP地址类型
    if (ip.toString().indexOf(':') >= 0) {
      Serial.println("Resolved to IPv6 address - this may cause ESP32 connection issues");
    } else {
      Serial.println("Resolved to IPv4 address");
    }
  } else {
    Serial.println("DNS resolution failed");
  }

  Serial.println("===================");
}

/**
 * @brief 进入配置模式
 * 
 * 修复说明:
 * - 添加了配置模式请求标志，确保在适当的时候重新启动配置模式
 * - 增加了状态重置和延迟，确保AP模式能够正确启动
 */
void enterConfigMode() {
  Serial.println("=== Entering Configuration Mode ===");
  
  // 设置配置模式请求标志
  configModeRequested = true;
  configModeRequestTime = millis();
  
  // 停止MQTT自动重连
  mqttManager.stopReconnect();

  // 断开MQTT连接
  mqttManager.disconnect();

  // 清空WiFi凭证
  wifiManager.clearWiFiCredentials();

  // 重置系统状态
  mqttInitialized = false;
  systemReady = false;
  mqttReconnectInProgress = false;

  Serial.println("System status reset, preparing for configuration mode...");
  
  // 显示等待信息
  displayManager.showStatus("Preparing", "Config Mode", "Please wait...");
  
  // 延迟确保操作完成
  delay(1000);
}

/**
 * @brief 处理配置模式重试逻辑
 * 
 * 修复说明:
 * - 分离了配置模式启动逻辑，确保在合适时机执行
 * - 添加了重试机制，防止AP模式启动失败
 */
void handleConfigModeRetry() {
  if (!configModeRequested) {
    return;
  }
  
  unsigned long currentTime = millis();
  
  // 检查是否到达重试时间
  if (currentTime - configModeRequestTime >= CONFIG_MODE_RETRY_DELAY) {
    Serial.println("Attempting to start configuration mode...");
    
    // 尝试启动配置模式
    if (wifiManager.startConfigMode()) {
      Serial.println("Configuration mode started successfully");
      configModeRequested = false;
      
      // 显示配置模式信息
      displayManager.showStatus("Config Mode", "AP: " + wifiManager.getAPName(), "IP: 192.168.4.1");
    } else {
      Serial.println("Configuration mode startup failed, will retry...");
      
      // 更新请求时间，准备下一次重试
      configModeRequestTime = currentTime;
      
      // 显示错误信息
      displayManager.showStatus("Config Error", "Failed to start AP", "Retrying...");
    }
  }
}

/**
 * @brief 初始化MQTT连接
 * @return true-初始化成功, false-初始化失败
 */
bool initializeMQTT() {
  Serial.println("Starting MQTT connection initialization...");

  // 允许MQTT重新连接
  mqttManager.allowReconnections();

  // 记录连接开始时间
  mqttConnectStartTime = millis();

  // 尝试初始化MQTT
  if (mqttManager.init()) {
    mqttInitialized = true;
    mqttReconnectInProgress = true;
    Serial.println("MQTT initialization successful - waiting for connection establishment");
    return true;
  } else {
    Serial.println("MQTT initialization failed");
    return false;
  }
}

/**
 * @brief 处理MQTT重连逻辑
 */
void handleMQTTReconnect() {
  unsigned long currentMillis = millis();

  // 如果正在配置模式，不进行MQTT重连
  if (wifiManager.isInConfigMode() || configModeRequested) {
    return;
  }

  // 检查连接超时
  if (mqttReconnectInProgress && !mqttManager.isConnected()) {
    if (currentMillis - mqttConnectStartTime > MQTT_CONNECT_TIMEOUT) {
      Serial.println("MQTT connection timeout, resetting connection status");
      mqttReconnectInProgress = false;
      mqttInitialized = false;
      lastMQTTReconnectAttempt = currentMillis;  // 立即重试
      return;
    }
  }

  // 检查是否需要尝试重连MQTT
  if (wifiManager.isWiFiConnected() && 
      !wifiManager.isInConfigMode() && 
      !mqttManager.isConnected() && 
      !mqttReconnectInProgress && 
      currentMillis - lastMQTTReconnectAttempt >= MQTT_RECONNECT_INTERVAL) {

    lastMQTTReconnectAttempt = currentMillis;

    Serial.println("=== MQTT Reconnection Attempt ===");
    Serial.print("WiFi status: ");
    Serial.println(wifiManager.isWiFiConnected() ? "Connected" : "Disconnected");
    Serial.print("Config mode: ");
    Serial.println(wifiManager.isInConfigMode() ? "Yes" : "No");
    Serial.print("MQTT connection status: ");
    Serial.println(mqttManager.isConnected() ? "Connected" : "Disconnected");
    Serial.print("MQTT initialization status: ");
    Serial.println(mqttInitialized ? "Initialized" : "Not initialized");

    if (!mqttInitialized) {
      // 首次初始化MQTT
      Serial.println("First time MQTT connection initialization...");
      if (initializeMQTT()) {
        Serial.println("MQTT initialization request sent");
      } else {
        Serial.println("MQTT initialization failed");
        mqttReconnectInProgress = false;
      }
    } else {
      // 已经初始化过，重新初始化
      Serial.println("Reinitializing MQTT connection...");
      mqttReconnectInProgress = true;
      mqttManager.allowReconnections();
      if (mqttManager.init()) {
        Serial.println("MQTT reinitialization request sent");
      } else {
        Serial.println("MQTT reinitialization failed");
        mqttReconnectInProgress = false;
      }
    }
  }

  // 如果MQTT连接成功，重置重连状态
  if (mqttManager.isConnected() && mqttReconnectInProgress) {
    mqttReconnectInProgress = false;
    systemReady = true;
    Serial.println("MQTT connection successful!");
    
    // 显示设备信息
    String deviceId = mqttManager.getTopicManager().getDeviceId();
    displayManager.showStatus("System Ready", "Device: " + deviceId, "WiFi & MQTT OK");
  }
}

/**
 * @brief 清除EEPROM中的损坏数据
 */
void clearCorruptedEEPROM() {
  Serial.println("Clearing corrupted data in EEPROM...");

  if (!EEPROM.begin(512)) {
    Serial.println("EEPROM initialization failed!");
    return;
  }

  // 只清除MQTT配置区域（96-228地址范围）
  for (int i = 96; i < 228; i++) {
    EEPROM.write(i, 0);
  }

  if (EEPROM.commit()) {
    Serial.println("EEPROM cleared successfully, MQTT configuration area reset");
  } else {
    Serial.println("EEPROM commit failed");
  }

  EEPROM.end();
}

/**
 * @brief Arduino setup函数 - 系统初始化
 */
void setup() {
  Serial.begin(115200);
  Serial.println("ESP32 MQTT Device Starting...");
  Serial.println("Development Board: ESP32-DevKitC V4");
  Serial.println("Version: 1.1.0 - Fixed AP mode issue");

  delay(3000);

  // 初始化GPIO
  initGPIO();

  // 网络协议配置
  Serial.println("Configuring network protocol...");

  // 启用IPv6支持（但我们会优先使用IPv4）
#ifdef CONFIG_LWIP_IPV6
  if (WiFi.enableIPv6(true)) {
    Serial.println("IPv6 support enabled");
    ipv6Available = true;
  } else {
    Serial.println("IPv6 enable failed, using IPv4");
    ipv6Available = false;
  }
#else
  Serial.println("IPv6 not compiled into firmware, using IPv4");
  ipv6Available = false;
#endif

  // 初始化各个管理器
  displayManager.init();

  // 从EEPROM加载间隔配置
  unsigned long loadedSensorInterval, loadedPublishInterval, loadedDisplayInterval;
  if (wifiManager.loadIntervalConfig(loadedSensorInterval, loadedPublishInterval, loadedDisplayInterval)) {
      // 使用保存的间隔配置
      sensorReadInterval = loadedSensorInterval;
      publishInterval = loadedPublishInterval;
      displayUpdateInterval = loadedDisplayInterval;
      
      Serial.println("Interval configuration loaded from EEPROM:");
      Serial.print("  Sensor interval: "); Serial.print(sensorReadInterval); Serial.println("ms");
      Serial.print("  Publish interval: "); Serial.print(publishInterval); Serial.println("ms");
      Serial.print("  Display interval: "); Serial.print(displayUpdateInterval); Serial.println("ms");
  } else {
      // 使用默认间隔配置
      sensorReadInterval = 500;
      publishInterval = 1000;
      displayUpdateInterval = 1000;
      
      Serial.println("Using default interval configuration:");
      Serial.print("  Sensor interval: "); Serial.print(sensorReadInterval); Serial.println("ms");
      Serial.print("  Publish interval: "); Serial.print(publishInterval); Serial.println("ms");
      Serial.print("  Display interval: "); Serial.print(displayUpdateInterval); Serial.println("ms");
      
      // 保存默认配置到EEPROM
      wifiManager.saveIntervalConfig(sensorReadInterval, publishInterval, displayUpdateInterval);
  }

  // 设置WiFi管理器的显示回调
  wifiManager.setDisplayCallback([](String line1, String line2, String line3) {
    displayManager.showStatus(line1, line2, line3);
  });

  // 设置MQTT显示刷新回调
  setDisplayRefreshCallback([]() {
    Serial.println("MQTT status changed, forcing display refresh");
    displayManager.forceRefresh();
  });

  // 设置传感器间隔回调
  setSensorIntervalCallback([](unsigned long newInterval) {
    sensorReadInterval = newInterval;
    Serial.println("Sensor reading interval updated: " + String(newInterval) + "ms");
    // 保存到EEPROM
    unsigned long currentPublishInterval, currentDisplayInterval;
    wifiManager.loadIntervalConfig(newInterval, currentPublishInterval, currentDisplayInterval); // 只为了获取当前值
    wifiManager.saveIntervalConfig(newInterval, currentPublishInterval, currentDisplayInterval);
  });

  // 设置发布间隔回调
  setPublishIntervalCallback([](unsigned long newInterval) {
    publishInterval = newInterval;
    Serial.println("Data publishing interval updated: " + String(newInterval) + "ms");
    // 保存到EEPROM
    unsigned long currentSensorInterval, currentDisplayInterval;
    wifiManager.loadIntervalConfig(currentSensorInterval, newInterval, currentDisplayInterval); // 只为了获取当前值
    wifiManager.saveIntervalConfig(currentSensorInterval, newInterval, currentDisplayInterval);
  });

  // 设置屏幕间隔回调
  setDisplayIntervalCallback([](unsigned long newInterval) {
    displayUpdateInterval = newInterval;
    Serial.println("Display update interval updated: " + String(newInterval) + "ms");
    // 保存到EEPROM
    unsigned long currentSensorInterval, currentPublishInterval;
    wifiManager.loadIntervalConfig(currentSensorInterval, currentPublishInterval, newInterval); // 只为了获取当前值
    wifiManager.saveIntervalConfig(currentSensorInterval, currentPublishInterval, newInterval);
  });

  // 显示启动信息
  displayManager.showStatus("System Starting", "Please wait...", "");

  // 初始化传感器
  if (aht10Sensor.init()) {
    Serial.println("AHT10 sensor initialized successfully");
  } else {
    Serial.println("AHT10 sensor initialization failed");
    displayManager.showStatus("Sensor Error", "AHT10 Not Found", "Check Wiring");
    delay(3000);
  }

  // 初始化WiFi
  if (wifiManager.init()) {
    // WiFi连接成功，显示网络信息
    diagnoseNetwork();
    testDNSResolution();

    // 等待WiFi稳定
    delay(2000);

    // 从EEPROM加载MQTT配置
    String mqttServer, mqttUser, mqttPassword;
    int mqttPort;

    Serial.println("Loading MQTT configuration...");
    if (wifiManager.loadMQTTCredentials(mqttServer, mqttPort, mqttUser, mqttPassword)) {
      Serial.println("Using saved MQTT configuration");
      Serial.print("Server: ");
      Serial.println(mqttServer);
      Serial.print("Port: ");
      Serial.println(mqttPort);
      Serial.print("User: ");
      Serial.println(mqttUser);
      Serial.print("Password length: ");
      Serial.println(mqttPassword.length());
      mqttManager.setMQTTServer(mqttServer, mqttPort, mqttUser, mqttPassword);
    } else {
      Serial.println("Using default MQTT configuration: test.mosquitto.org:1883");
      mqttManager.setDefaultServer();
    }

    // WiFi连接成功，初始化MQTT
    if (initializeMQTT()) {
      systemReady = true;
      mqttInitialized = true;

      // 显示设备信息
      String deviceId = mqttManager.getTopicManager().getDeviceId();
      displayManager.showStatus("System Ready", "Device: " + deviceId, "WiFi & MQTT OK");
      
      Serial.println("System ready: WiFi and MQTT connected successfully");
    } else {
      displayManager.showStatus("MQTT Error", "Check Server", "Will Retry");
      Serial.println("MQTT connection failed, will retry in background");
      mqttInitialized = false;
    }
  } else {
    // WiFi初始化失败，进入配置模式
    Serial.println("WiFi initialization failed, entering configuration mode");
    enterConfigMode();
  }

  // 确保屏幕状态正确显示
  Serial.print("Final screen status: ");
  Serial.println(displayManager.isDisplayOn() ? "ON" : "OFF");
}

/**
 * @brief Arduino loop函数 - 主循环
 */
void loop() {
  // 处理WiFi事件
  wifiManager.handleClient();

  // 处理配置模式重试
  handleConfigModeRetry();

  // 更新非阻塞WiFi重连
  wifiManager.updateReconnect();

  // 检查按钮状态
  checkButton();

  // 处理MQTT重连
  handleMQTTReconnect();

  // 检查WiFi连接状态，如果断开且不在配置模式，开始重连
  if (!wifiManager.isWiFiConnected() && !wifiManager.isInConfigMode() && !configModeRequested && !wifiManager.isReconnecting()) {
    wifiManager.startReconnect();
  }

  unsigned long currentMillis = millis();

  // 定时检查WiFi信号强度
  if (currentMillis - lastWifiCheck >= WIFI_CHECK_INTERVAL) {
    lastWifiCheck = currentMillis;

    // 更新WiFi信号强度显示
    int rssi = WiFi.RSSI();
    displayManager.updateWifiStrength(rssi);
  }

  // 定时读取传感器数据并发布 - 无论MQTT状态如何都读取，但只在连接时发布
  if (currentMillis - lastSensorRead >= sensorReadInterval && !wifiManager.isInConfigMode()) {
      lastSensorRead = currentMillis;

      if (aht10Sensor.isSensorFound()) {
          if (aht10Sensor.readData()) {
              float temperature = aht10Sensor.getTemperature();
              float humidity = aht10Sensor.getHumidity();
              int rssi = WiFi.RSSI();

              Serial.printf("Sensor data read: %.1f°C, %.1f%%, RSSI: %d dBm\n", temperature, humidity, rssi);

              // 发布逻辑 - 使用动态间隔
              if (mqttManager.isConnected() && (currentMillis - lastPublishTime >= publishInterval)) {
                  lastPublishTime = currentMillis;
                  Serial.println("Publishing sensor data and WiFi signal strength to MQTT...");
                  mqttManager.publishSensorData(temperature, humidity, rssi);
              }
          } else {
              Serial.println("Failed to read sensor data");
          }
      } else {
          Serial.println("Sensor not found");
      }
  }

  // 定时更新显示 - 只在屏幕开启时更新，使用动态间隔
  if (currentMillis - lastDisplayUpdate >= displayUpdateInterval && displayManager.isDisplayOn()) {
      lastDisplayUpdate = currentMillis;

      if (wifiManager.isInConfigMode()) {
          // 配置模式下显示配置信息
          displayManager.showStatus("Config Mode", "AP: " + wifiManager.getAPName(), "IP: 192.168.4.1");
      } else if (aht10Sensor.isSensorFound()) {
          // 无论WiFi状态如何，只要传感器正常就显示温湿度数据
          float temperature = aht10Sensor.getTemperature();
          float humidity = aht10Sensor.getHumidity();
          int rssi = WiFi.RSSI();
          String ssid = WiFi.SSID();
          bool wifiConnected = wifiManager.isWiFiConnected();
          bool mqttConnected = mqttManager.isConnected();

          displayManager.showSimpleWeatherData(temperature, humidity, rssi, wifiConnected, mqttConnected, ssid);
      } else {
          // 传感器未找到时的显示逻辑
          if (wifiManager.isWiFiConnected()) {
              String deviceId = mqttManager.getTopicManager().getDeviceId();
              displayManager.showStatus("Device: " + deviceId, 
                                        "MQTT " + String(mqttManager.isConnected() ? "Connected" : "Disconnected"), 
                                        "Sensor Not Found");
          } else {
              displayManager.showStatus("WiFi Disconnected", "Reconnecting...", "");
          }
      }
      
      // 调试信息：显示当前间隔
      static unsigned long lastDebugDisplay = 0;
      if (currentMillis - lastDebugDisplay >= 5000) {
          lastDebugDisplay = currentMillis;
          Serial.print("Current display update interval: ");
          Serial.print(displayUpdateInterval);
          Serial.println("ms");
      }
  }

  // 简单的状态检查 - 每1秒检查一次MQTT状态变化
  static unsigned long lastStatusCheck = 0;
  static bool lastMQTTState = false;

  if (currentMillis - lastStatusCheck >= STATUS_CHECK_INTERVAL) {
    lastStatusCheck = currentMillis;

    bool currentMQTTState = mqttManager.isConnected();
    if (currentMQTTState != lastMQTTState) {
      Serial.print("[Status Change] MQTT: ");
      Serial.println(currentMQTTState ? "Connected" : "Disconnected");
      lastMQTTState = currentMQTTState;
      displayManager.forceRefresh();  // 状态变化时强制刷新
    }
  }

  // 定时更新显示 - 只在屏幕开启时更新
  if (currentMillis - lastDisplayUpdate >= displayUpdateInterval && displayManager.isDisplayOn()) {
    lastDisplayUpdate = currentMillis;

    if (wifiManager.isInConfigMode() || configModeRequested) {
      // 配置模式下显示配置信息
      if (wifiManager.isInConfigMode()) {
        displayManager.showStatus("Config Mode", "AP: " + wifiManager.getAPName(), "IP: 192.168.4.1");
      } else {
        displayManager.showStatus("Preparing", "Config Mode", "Please wait...");
      }
    } else if (aht10Sensor.isSensorFound()) {
      // 无论WiFi状态如何，只要传感器正常就显示温湿度数据
      float temperature = aht10Sensor.getTemperature();
      float humidity = aht10Sensor.getHumidity();
      int rssi = WiFi.RSSI();
      String ssid = WiFi.SSID();
      bool wifiConnected = wifiManager.isWiFiConnected();
      bool mqttConnected = mqttManager.isConnected();

      displayManager.showSimpleWeatherData(temperature, humidity, rssi, wifiConnected, mqttConnected, ssid);
    } else {
      // 传感器未找到时的显示逻辑
      if (wifiManager.isWiFiConnected()) {
        String deviceId = mqttManager.getTopicManager().getDeviceId();
        displayManager.showStatus("Device: " + deviceId, 
                                 "MQTT " + String(mqttManager.isConnected() ? "Connected" : "Disconnected"), 
                                 "Sensor Not Found");
      } else {
        displayManager.showStatus("WiFi Disconnected", "Reconnecting...", "");
      }
    }
  }

  // 主循环延迟
  delay(100);
}